﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Affector/Velocity/AccelerationOverLifetime")]
public class PUEXAccelerationOverLifetimeAffector : PUEXAffector {

	#region - Editable property
	public PUEXDynamicAttribute accelerationX;
	public PUEXDynamicAttribute accelerationY;
	public PUEXDynamicAttribute accelerationZ;
	public bool useEmitterTime;
	public bool inWorldSpace;
	#endregion
	
	#region - Lifecycle
	public PUEXAccelerationOverLifetimeAffector ()
	{
		accelerationX = PUEXDynamicAttribute.GenerateFixed(1f);
		accelerationY = PUEXDynamicAttribute.GenerateFixed(1f);
		accelerationZ = PUEXDynamicAttribute.GenerateFixed(1f);
		useEmitterTime = false;
		inWorldSpace = true;
	}
	#endregion
	
	#region - Update
	public override void update (float dt, PUEXParticle particle)
	{
		float t = particle.timeFraction;
		if (useEmitterTime)
			t = inTrigger() ? triggerTimeFraction : ownerEmitter.timeFraction;

		Vector3 acceleration = new Vector3 (accelerationX.getValue(t),
		                                    accelerationY.getValue(t),
		                                    accelerationZ.getValue(t));
		if (inWorldSpace) {
			if (ownerEmitter.keepLocal) {
				Matrix4x4 invMat = ownerEmitter.ownerParticleSystem.systemToWorldTransform.inverse;
				acceleration = invMat.MultiplyVector(acceleration);
			}
		} else {
			if (!ownerEmitter.keepLocal) {
				acceleration = ownerEmitter.ownerParticleSystem.systemToWorldTransform.MultiplyVector(acceleration);
			}
		}

		particle.setVelocity (particle.velocity() + acceleration * dt);
	}
	#endregion

	#region - Param property
	public override void updateParams (PUEXParticleSystem system)
	{
		accelerationX.parameterize (system);
		accelerationY.parameterize (system);
		accelerationZ.parameterize (system);
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData emitterData, JsonData systemData)
	{
		JsonData ret = base.save (emitterData, systemData);

		ret ["acceleration_x"] = PUEXUtils.serializeDynamicAttribute(accelerationX);
		ret ["acceleration_y"] = PUEXUtils.serializeDynamicAttribute(accelerationY);
		ret ["acceleration_z"] = PUEXUtils.serializeDynamicAttribute(accelerationZ);
		ret ["use_emitter_time"] = useEmitterTime;
		ret ["in_world_space"] = inWorldSpace;
		
		return ret;
	}
	#endregion

}
